//
//  SDregisterViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/10.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDRegisterViewController.h"
#import "SDLoginLTView.h"
#import "SDCountDownButton.h"
#import "SDRegisterData.h"
#import "SDFogetPswdData.h"
#import "SDSMSVerifyCodeData.h"

#define kMarginLeftWidth 18
#define kVerificationCodeBtnWidth 50

@interface SDRegisterViewController()<SDFormBaseDataDelegate,UITableViewDataSource, UITableViewDelegate,SDFormBaseDataDelegate>
@property(nonatomic,strong)UITableView* tableView;

@property(nonatomic,strong)SDLoginLTView* mobileNumberView;
@property(nonatomic,strong)SDLoginLTView* verificationCodeView;
@property(nonatomic,strong)SDLoginLTView* pswdView;
@property(nonatomic,strong)SDLoginLTView* confirmPswdView;
@property(nonatomic,strong)SDCountDownButton* countDownBtn;

@property(nonatomic,strong)SDRegisterData* registerData;
@property(nonatomic,strong)SDFogetPswdData* forgetPswdData;
@property(nonatomic,strong)SDSMSVerifyCodeData* verifyCodeData;

@end

@implementation SDRegisterViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initSubviews];
    [self initData];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear: animated];
    [self dismissKeyboard];
}

-(void)initData
{
    if (_type == 1) {
        _forgetPswdData = [[SDFogetPswdData alloc] init];
        _forgetPswdData.delegate = self;
    } else {
        _registerData = [[SDRegisterData alloc] init];
        _registerData.delegate = self;
    }

    _verifyCodeData = [[SDSMSVerifyCodeData alloc] init];
    _verifyCodeData.delegate = self;
}

-(void)initSubviews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        if (_type == 1) {
            [self.navBar setTitle:@"忘记密码"];
        } else {
            [self.navBar setTitle:@"注册"];
        }

        UIImage* backImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:backImg];
        [self.navBar customNaviRightButton:self action:@selector(onDone:) title:@"完成"];
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _tableView = [[UITableView alloc] initWithFrame:autoRectTableViewHaveBar(YES) style:UITableViewStylePlain];
    // _tableView.backgroundColor = [UIColor colorWithRGB:0xf9fafc];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)showLoading{
    [self finishLoading];
    [VPMBProgressHUD showIndicatorWithText:@"等待中"];
}

- (void)finishLoading
{
    [VPMBProgressHUD hideIndicator];
}

-(void)addCountDownView
{
    _countDownBtn = [SDCountDownButton buttonWithType:UIButtonTypeCustom];
    [_countDownBtn setBackgroundColor:[UIColor colorWithRGB:0x24d9c6]];
    [_countDownBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_countDownBtn setTitleColor:[UIColor colorWithRGB:0xffffff] forState:UIControlStateNormal];
    _countDownBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    _countDownBtn.frame = CGRectMake(0, 0, 0, 30);
    _countDownBtn.layer.cornerRadius = 14;
    _countDownBtn.clipsToBounds = YES;
    [_countDownBtn sizeToFit];
    _countDownBtn.top = (_verificationCodeView.height - _countDownBtn.height)/2;
    NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
    CGSize size = [_countDownBtn.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, _countDownBtn.frame.size.height) options:NSStringDrawingTruncatesLastVisibleLine attributes:attribute context:nil].size;
    _countDownBtn.width = size.width + 20;
    _countDownBtn.right = kScreenWidth - 15;
    [_verificationCodeView addSubview:_countDownBtn];
    
    __weak __typeof(self)weakSelf = self;
    [_countDownBtn addToucheHandler:^(SDCountDownButton* sender, NSInteger tag) {
        sender.enabled = NO;
        if (!CHECK_VALID_STRING(weakSelf.mobileNumberView.textField.text)){
            [SDAlertManagement showNormalErrorAlert:@"获取验证码的手机号不能为空"];
            return;
        }
        if (_type == 1) {
            weakSelf.verifyCodeData.type = 2;
        } else {
            weakSelf.verifyCodeData.type = 1;
        }
        weakSelf.verifyCodeData.mobileNumber = weakSelf.mobileNumberView.textField.text;
        [weakSelf.verifyCodeData uploadFormDataWithUserInfo:nil];
        [sender startWithSecond:60];
        
        [sender didChange:^NSString *(SDCountDownButton *countDownButton,int second) {
            NSString *title = [NSString stringWithFormat:@"剩余%d秒",second];
            return title;
        }];
        [sender didFinished:^NSString *(SDCountDownButton *countDownButton, int second) {
            countDownButton.enabled = YES;
            NSString* title = @"重新获取";
            return title;
        }];
        
    }];
}


-(void)dismissKeyboard
{
    [_mobileNumberView.textField resignFirstResponder];
    [_verificationCodeView.textField resignFirstResponder];
    [_pswdView.textField resignFirstResponder];
    [_confirmPswdView.textField resignFirstResponder];
}


-(UIView*)cretateSeparatorLineView
{
    UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    [separatorLineView setBackgroundColor:[UIColor colorWithRGB:0xcad6e3]];
    return separatorLineView;
}

-(void)animateTextField:(UITextField*)textField up:(BOOL)up
{
    const int movementDistance = -20;
    const float movementDuration = 0.3f;
    
    int movement = (up ? movementDistance : -movementDistance);
    
    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}

#pragma mark UI Event
- (void)onBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)onDone:(id)sender
{
    if (!CHECK_VALID_STRING(_mobileNumberView.textField.text)){
        [SDAlertManagement showNormalErrorAlert:@"手机号不能为空"];
        return;
    }
    if (!CHECK_VALID_STRING(_verificationCodeView.textField.text)){
        [SDAlertManagement showNormalErrorAlert:@"验证码不能为空"];
        return;
    }
    if (!CHECK_VALID_STRING(_pswdView.textField.text)){
        [SDAlertManagement showNormalErrorAlert:@"新密码不能为空"];
        return;
    }
    if (!CHECK_VALID_STRING(_confirmPswdView.textField.text)){
        [SDAlertManagement showNormalErrorAlert:@"确认不能为空"];
        return;
    }
    
    if (![_pswdView.textField.text isEqualToString: _confirmPswdView.textField.text]) {
        [SDAlertManagement showNormalErrorAlert:@"输入的密码不一致"];
        return;
    }
    
    if (_type == 1) {
        _forgetPswdData.password = _pswdView.textField.text;
        _forgetPswdData.mobileNumber = _mobileNumberView.textField.text;
        _forgetPswdData.verifyCode = _verificationCodeView.textField.text;
        [_forgetPswdData excuteHttpRequest];
    } else {
        _registerData.password = _pswdView.textField.text;
        _registerData.mobileNumber = _mobileNumberView.textField.text;
        _registerData.verifyCode = _verificationCodeView.textField.text;
        [_registerData uploadFormDataWithUserInfo:nil];
    }
    
    [self dismissKeyboard];
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    if (row == 0) {
        return 40;
    }
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    
    if (row == 0) {
        UITableViewCell* cell = nil;
        static NSString* identifier = @"blankCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.backgroundColor = [UIColor clearColor];
            
            UIView* separatorLine = [self cretateSeparatorLineView];
            separatorLine.bottom = cell.bottom;
            [cell.contentView addSubview:separatorLine];
        }
        return cell;
    }else if (row == 1) {
        UITableViewCell* cell = nil;
        static NSString* identifier = @"mobileNumberCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _mobileNumberView = [[SDLoginLTView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) delegate:self];
            [_mobileNumberView setName:@"手机号"];
            [cell.contentView addSubview:_mobileNumberView];
            UIView* separatorLine = [self cretateSeparatorLineView];
            separatorLine.width = kScreenWidth - 2*kMarginLeftWidth;
            separatorLine.left = kMarginLeftWidth;
            separatorLine.top = _mobileNumberView.bottom;
            [cell.contentView addSubview:separatorLine];
        }
        return cell;
    } else if (row == 2) {
        UITableViewCell* cell = nil;
        static NSString* identifier = @"verificationCodeCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _verificationCodeView = [[SDLoginLTView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) delegate:self];
            _verificationCodeView.textField.width = _verificationCodeView.width - _verificationCodeView.nameLabel.width - 100;
            [_verificationCodeView setName:@"验证码"];
            [cell.contentView addSubview:_verificationCodeView];
            [self addCountDownView];
            UIView* separatorLine = [self cretateSeparatorLineView];
            separatorLine.width = kScreenWidth - 2*kMarginLeftWidth;
            separatorLine.left = kMarginLeftWidth;
            separatorLine.top = _verificationCodeView.bottom;
            [cell.contentView addSubview:separatorLine];
            
        }
        return cell;
    } else if (row == 3) {
        UITableViewCell* cell = nil;
        static NSString* identifier = @"pswdCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _pswdView = [[SDLoginLTView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) delegate:self];
            [_pswdView setName:@"密码"];
            [cell.contentView addSubview:_pswdView];
            UIView* separatorLine = [self cretateSeparatorLineView];
            separatorLine.width = kScreenWidth - 2*kMarginLeftWidth;
            separatorLine.left = kMarginLeftWidth;
            separatorLine.top = _pswdView.bottom;
            [cell.contentView addSubview:separatorLine];
            
            _pswdView.textField.secureTextEntry = YES;
            _pswdView.textField.autocorrectionType = UITextAutocorrectionTypeNo;
            _pswdView.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
            _pswdView.textField.returnKeyType = UIReturnKeyDone;
            _pswdView.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        }
        return cell;
    }
    else if (row == 4) {
        UITableViewCell* cell = nil;
        static NSString* identifier = @"cofirmPswdCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _confirmPswdView = [[SDLoginLTView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) delegate:self];
            [_confirmPswdView setName:@"确认密码"];
            [cell.contentView addSubview:_confirmPswdView];
            UIView* separatorLine = [self cretateSeparatorLineView];
            separatorLine.top = _confirmPswdView.bottom;
            [cell.contentView addSubview:separatorLine];
            
            _confirmPswdView.textField.secureTextEntry = YES;
            _confirmPswdView.textField.autocorrectionType = UITextAutocorrectionTypeNo;
            _confirmPswdView.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
            _confirmPswdView.textField.returnKeyType = UIReturnKeyDone;
            _confirmPswdView.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        }
        return cell;
    }
    
    
    return nil;
}

#pragma mark - UIScrollView
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self dismissKeyboard];
}

#pragma mark SDFormBaseDataDelegate
-(void) willUploadOfFormData:(SDFormBaseData*) formdata
{
    if ([formdata isKindOfClass:[SDRegisterData class]] || [formdata isKindOfClass:[SDFogetPswdData class]]){
        [self showLoading];
    }
}

-(void) formData:(SDFormBaseData*)formdata userInfo:(NSDictionary*) userInfo didFinishLoadWithError:(NSError*)error
{
    [self finishLoading];
    if (error == nil) {
        if ([formdata isKindOfClass:[SDSMSVerifyCodeData class]]) {
            
        } else if ([formdata isKindOfClass:[SDRegisterData class]])
        {
            [self onBack:nil];
        }  else if ([formdata isKindOfClass:[SDFogetPswdData class]])
        {
            [self onBack:nil];
        }
    } else {
        NSString* errorStr = [NSString stringWithFormat:@"%@:%@",[error.userInfo objectForKey:@"SDHttpRequest_ResponseInfo"],[error.userInfo objectForKey:@"SDHttpRequest_ResponseCode"]];
        if ([[error.userInfo objectForKey:@"SDHttpRequest_ResponseCode"] integerValue] == 6 && self.type == 1) {
            [_countDownBtn stop];
            [SDAlertManagement showNormalErrorAlert:@"手机号未注册"];
            return;
            
        }
            
        [SDAlertManagement showNormalErrorAlert:errorStr];
    }
}

@end
